package com.example.service.impl;


import cn.hutool.dfa.WordTree;
import com.example.DTO.CommentDTO;
import com.example.mapper.CommentMapper;
import com.example.pojo.Comment;
import com.example.pojo.User;
import com.example.service.CommentService;
import com.example.service.UserService;
import com.example.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserService userService;


    private final WordTree wordTree = new WordTree();

    // 初始化敏感词（实际项目可改为从数据库加载）
    private final List<String> SENSITIVE_WORDS = Arrays.asList(
            "垃圾", "暴力", "色情", "傻逼", "fuck",
            "操", "违禁词", "政治", "反动","你妈",
            "傻子","共产党","废物","畜生","傻叉","操","傻B"
    );

    @PostConstruct
    public void init() {
        // 添加敏感词到DFA树
        wordTree.addWords(SENSITIVE_WORDS);
    }

    /**
     * 过滤敏感词（替换为***）
     * @param text 原始文本
     * @return 过滤后的文本
     */
    public String filter(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }

        // Hutool 5.7.17版本的替换方式
        List<String> foundWords = wordTree.matchAll(text);
        for (String word : foundWords) {
            text = text.replace(word, "***");
        }
        return text;
    }

    /**
     * 检查是否包含敏感词
     * @param text 待检查文本
     * @return 是否包含敏感词
     */
    public boolean containsSensitiveWord(String text) {
        return !wordTree.matchAll(text).isEmpty();
    }


    @Override
    public void add(Comment comment) {
        Claims claims = ThreadLocalUtil.get();
        Integer userid = (Integer) claims.get("id");
        comment.setUserId(userid);
        comment.setCreateTime(LocalDateTime.now());
        comment.setParentId(0);//主评论的父id为0
        comment.setPregnant(0);//初始化都无子评论为0

        // 过滤敏感词
        String filteredContent = filter(comment.getContent());
        comment.setContent(filteredContent);

        // 检查是否包含敏感词，如果包含则抛出异常或进行处理
        if (containsSensitiveWord(comment.getContent())) {
            throw new IllegalArgumentException("评论内容包含敏感词，请修改后再提交");
        }
        commentMapper.add(comment);
    }

    @Override
    public List<CommentDTO> list(Integer articleId) {
        List<Comment> list = commentMapper.list(articleId);
        List<CommentDTO> commentDTOList =  new ArrayList<>();
        //构造List<CommentDTO>
        for (Comment comment : list) {
            CommentDTO commentDTO = new CommentDTO();
            // Spring BeanUtils
            BeanUtils.copyProperties(comment, commentDTO); // 注意参数顺序
            User user = userService.findById(comment.getUserId());
            commentDTO.setNickname(user.getNickname());
            commentDTO.setUser_pic(user.getUserPic());
            commentDTOList.add(commentDTO);
        }
        //按照创建时间升序排序
        commentDTOList.sort(Comparator.comparing(CommentDTO::getCreateTime).reversed());
        return commentDTOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reply(Comment comment) {
        Claims claims = ThreadLocalUtil.get();
        Integer userid = (Integer) claims.get("id");
        comment.setUserId(userid);
        comment.setCreateTime(LocalDateTime.now());
        comment.setPregnant(0);

        // 过滤敏感词
        String filteredContent = filter(comment.getContent());
        comment.setContent(filteredContent);

        // 检查是否包含敏感词，如果包含则抛出异常或进行处理
        if (containsSensitiveWord(comment.getContent())) {
            throw new IllegalArgumentException("评论内容包含敏感词，请修改后再提交");
        }
        //让父评论怀孕
        commentMapper.makepregnant(comment.getParentId());
        commentMapper.add(comment);
    }

    @Override
    public List<CommentDTO> listChild(Integer parentId) {
        //查询创建父评论的用户id
        Integer replyUserId =  commentMapper.getUseridByParentId(parentId);
        List<Comment> list = commentMapper.listChild(parentId);
        List<CommentDTO> commentDTOList =  new ArrayList<>();
        //构造List<CommentDTO>
        for (Comment comment : list) {
            CommentDTO commentDTO = new CommentDTO();
            // Spring BeanUtils
            BeanUtils.copyProperties(comment, commentDTO); // 注意参数顺序
            User user = userService.findById(comment.getUserId());
            commentDTO.setNickname(user.getNickname());
            commentDTO.setUser_pic(user.getUserPic());
            commentDTO.setReplyUserId(replyUserId);
            commentDTOList.add(commentDTO);
        }
        //按照创建时间升序排序
        commentDTOList.sort(Comparator.comparing(CommentDTO::getCreateTime).reversed());
        return commentDTOList;
    }
}
